#!/usr/bin/env python
#coding:utf8
import daemon
import os.path
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import time
import uuid
import datetime
import json
import tts
import traceback

from tornado.options import define, options
define("port", default=2020, help="run on the given port", type=int)

class ttswHandler(tornado.web.RequestHandler):
    def get(self):
        html =  """
        <!DOCTYPE html>
        <html>
        <style>
        #all{
	width: 800px;
	height: 450px;
	border: 1px solid green;
	position:absolute;
        top:50%;
        left:50%;
        margin:-225px 0 0 -400px;
       }
        </style>
        <body>
        <div id = "all">
        <form id="usrform" action="/tts_web" method="post">
        <textarea name="text"  rows="15" style="width:100%; overflow: auto;" form="usrform"></textarea>
        <p>语言: <input type="text"  list="lang"  name="language" />
        <datalist id="lang">
        <option value ="cn">
        <option value ="en">
        </datalist>
        </p>
        <p>发音: <input type="text" list="role" name="role">
        <datalist id="role">
        <option value ="xiaoyun">
        <option value ="aitong">
        </datalist>
        </p>
        <input type="submit" value="提交" />
        </form>
        </div>
        </body>
        </html>
        """
        self.finish(html)
    def post(self):
        role = self.get_argument("role")
        text = self.get_argument("text")
        language = self.get_argument("language", default="cn")
        self.set_header('Content-Type', "text/plain")
        mp3 = tts.LTTS(role, text)
        self.finish(mp3)

def main():
    tornado.options.parse_command_line()
    application = tornado.web.Application([
            (r"/tts_web", ttswHandler),
        ],
        template_path = os.path.join(os.path.dirname(__file__), "templates"),
        static_path = os.path.join(os.path.dirname(__file__), "static"),
        debug = True,
        #cookie_secret="xiechc@gmail.com",
        )
        

    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.current().start()

if __name__ == "__main__":
    while True:
        try:
            daemon.daemonize("/tmp/teach.pid")
            main()
        except Exception:
            f = open("/tmp/errstr", "a")
            traceback.print_exc(file=f)
            f.close()

